<?php

@include_once('./database.php');

// 购物车的逻辑
//   判断该商品是否已经存在
//         存在   num+1
//         不存在  插入


$uname = $_POST['username'];
$id = $_POST['goods_id'];
$num = $_POST['num'];

// $uname = 'yy' ;
// $id = 1 ;
// $num = 1 ;


$obj = [];

if ($uname && $id && $num) {
    // 判断购物车中yy是否买了该商品
    $sql = "select * from cart where goods_id = $id and user_name = '$uname'";
    $res = mysqli_query($connect, $sql);
    $arr = mysqli_fetch_array($res);
    if ($arr) {
        // 如果已经找到了  就修改数量
        $sql = "UPDATE cart set cart_num = cart_num + $num where user_name = '$uname' and goods_id = $id";
        mysqli_query($connect, $sql);
        // 受影响的行数
        $rows = mysqli_affected_rows($connect);
        if ($rows > 0) {
            $obj['status'] = true;
            $obj['msg'] = '成功加入购物车';
        } else {
            $obj['status'] = false;
            $obj['msg'] = '服务器错误';
        }
    } else {
        // 如果没有找到  就插入数据
        $sql = "insert into cart (user_name , goods_id , cart_num) values ('$uname' , $id , $num)";
        mysqli_query($connect, $sql);
        // 受影响的行数
        $rows = mysqli_affected_rows($connect);
        if ($rows > 0) {
            $obj['status'] = true;
            $obj['msg'] = '成功加入购物车';
        } else {
            $obj['status'] = false;
            $obj['msg'] = '服务器错误';
        }
    }
} else {
    $obj['status'] = false;
    $obj['msg'] = '前端数据有误';
}



// 返回给前端的数据  --- json格式的字符串
echo (json_encode($obj, JSON_UNESCAPED_UNICODE));
